import sys,os,time,subprocess
#具体测试用例，必须test开头
def test_monkey():
    
    try:
        logfilename =  sys.path[0] + '/monkeylogs/' + 'e3b336c7' + '_monkey_' + time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime()) + '.txt'
        
        with open(logfilename, 'w', encoding='utf-8') as f:
            testcmd = 'adb -s e3b336c7 shell monkey -p com.vivo.testing.crashapp  --pct-touch 100  --ignore-crashes --ignore-timeouts --monitor-native-crashes  --throttle 100 -s 1234  -v-v-v 500'

            f.write(testcmd + '\r\n')

            ps = subprocess.Popen(testcmd, shell=True,stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
        
            rt = False
            reason = 'not run finished'
            while True:
                line = ps.stdout.readline()

                data = bytes.decode(line)
                print("收到"+data)

                if data == '':
                    break
                f.write(data)

                if data.find('// Monkey finished')>=0:
                    if reason == 'not run finished':
                        rt = True
                        reason == 'finished'
                elif data.find('** Monkey aborted due to error')>=0:
                    rt = False
                    if reason == 'not run finished':
                        reason = 'Monkey aborted due to error'
                elif data.find('// CRASH:')>=0 or data.find('// NOT RESPONDING:')>=0 or data.find('New native crash detected')>=0:
                    rt = False
                    reason = data
            ps.stdout.close()

    except Exception as e:
        print(e)


if __name__ == '__main__':
    test_monkey()
